<?php

/**
 * Created by PhpStorm.
 * User: gongxiaohua
 * Date: 17年2月22日
 * Time: 上午10:14
 */
namespace Warehouse\Service;

use Inbound\Service\PublicInfoService;

class PurchaseordersService {
    public $Purchaseorder_details = NULL;
    public $Recieve_details = NULL;
    public $Recieve_manual_pics = NULL;
    public $Recieve_pics__details = NULL;

    //查询记录总数
    public $count = 0;
    //页面展示包含页面样式
    public $page = 0;
    //数据
    public $data = array ();

    public $Purchaseorder_details_data = array ();

    public $nowtime;

    /**
     * PurchaseordersService constructor.
     * @param string $table
     * @param array  $param
     */
    public function __construct ($table = '', $param = array ()) {
        $this->nowtime                     = date('Y-m-d H:i:s', time());
        $this->Purchaseorder_details       = D('Warehouse/PurchaseOrderDetails', 'Model');
        $this->Purchaseorder_details_sites = D('Warehouse/PurchaseOrderDetailsSites', 'Model');
        $this->Recieve_details             = D('Warehouse/RecieveDetails', 'Model');
        //$this->Recieve_manual_pics   = D('RecieveManualPics','Model');
        //$this->Recieve_pics_details  = D('RecievePicsDetails','Model');
    }

    /**
     * @param array $_array
     * @param bool  $flag
     * @return mixed
     * 扫描收货页面数据查询与显示
     */
    public function purchased_wait_recieve ($_array = '', $flag = TRUE) {
        $_array = empty($_array)?$_GET:$_array;
        $model  = $this->Purchaseorder_details->get_purchaseorders_model($_array, $flag);

        if ($flag) {
            $Purchaseorder_details = clone $model;
            $this->count           = $Purchaseorder_details->count();//数量
            $Page                  = new \Org\Util\Page($this->count, 20);// 实例化分页类 传入总记录数和每页显示的记录数(5)
            $this->page            = $Page->show();// 分页显示输出

            $model->order("c.id desc")
                ->limit($Page->firstRow.','.$Page->listRows);
        }
        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $result = $model->select();
        $result = $this->format_purchased_wait_recieve($result);
        return $result;
    }

    /**
     * 收获确认
     */
    public function check ($_array = '', $flag = TRUE) {
        $_array = empty($_array)?$_GET:$_array;
        $model  = $this->Purchaseorder_details->get_purchaseorders_model($_array, $flag);
        $result = $model->order('c.id asc')
            ->select();
        return $result;
    }

    /**
     * 创建收货图片明细
     */

    public function create_recieve_pic_details ($_array) {

        $this->data = array (
            'recieve_manual_pic_id' => $_array['recieve_manual_pic_id'],
            'uploader_id'           => $_SESSION['current_account']['id'],
            'upload_time'           => $this->nowtime,
            'url'                   => $_array['url'],
        );

        $opsign = $this->Recieve_pics_details->add_recieve_pics_details($this->data);
        if ($opsign) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    /**
     * 删除图片
     */

    public function delPic ($picurl) {
        $opsign = $this->Recieve_pics_details->delPic($picurl);
        return $opsign;
    }

    /**
     *创建收获单
     */
    public function create_recieve ($_array, $batch_code, $arrival_quantity, &$model = NULL) {
        $model      = $model == NULL?$this->Recieve_details->model:$model;
        $this->data = array (
            'warehouseid'         => $_array[0]['mainwarehouseid'],
            'purchaseorder_id'    => $_array[0]['id'],
            'recieve_time'        => $this->nowtime,
            'recieve_man'         => $_SESSION['current_account']['id'],
            'purchase_id'         => $_array[0]['purchase_id'],
            'supplier'            => $_array[0]['supplier_id'],
            'store'               => $_array[0]['store'],
            'export_tax_rebate'   => $_array[0]['export_tax_rebate'],
            'enterprise_dominant' => $_array[0]['enterprise_dominant'],
            'transfer_hopper_id'  => $_array[0]['transfer_hopper_id'],
            'transfer_type'       => $_array[0]['transfer_type'],
        );
        $this->Recieve_details->add_recieve_invoices_table($this->data, $model);

        /*$this->Recieve_manual_pics->add_recieve_manual_pics(array(
            'purchaseorder_id'=>$_array[0]['id'],
            'recieve_invoice_id'=>$this->Recieve_details->Recieve_invoices_id,
            'reciever_id'=>$_SESSION['current_account']['id'],
            ' recieve_time '=>$this->nowtime));*/
        $update_sku = '';
        foreach ($_array as $key => $sku) {
            $update_sku[$sku['sku']] += intval($arrival_quantity[$key]);
        }
        if ($this->Recieve_details->Recieve_invoices_id) {
            foreach ($_array as $key => $detail) {
                $Recieve_details_data = array (
                    'warehouseid'        => $detail['warehouseid'],
                    'batch_code'         => $batch_code,
                    'recieve_invoice_id' => $this->Recieve_details->Recieve_invoices_id,
                    'sku'                => $detail['sku'],
                    'sku_name'           => $detail['sku_name'],
                    'sku_standard'       => $detail['sku_standard'],
                    'storage_position'   => $detail['storage_position'],
                    'purchase_quantity'  => $detail['quantity'],
                    'site_id'            => $detail['site_id'],
                    'arrival_quantity'   => intval($arrival_quantity[$key]),
                    //插入时判断是否
                    'check_count'        => 0,
                    'skuchecksign'       => PublicdataService::ckeck_sku_sign($detail['sku']) == ''?0:10,
                );

                $skuLogistic                            = D('CheckOrders', 'Service')->get_logic_v($detail['sku']);
                $Recieve_details_data['logisticsCheck'] = $skuLogistic == ''?0:20;

                $this->Recieve_details->add_recieve_details_table($Recieve_details_data, $model);

                //1.回传收货数量、状态到采购明细表  以及回传数量到采购订单站点明细表
                $this->Purchaseorder_details_sites->setInc_purchaseorder_details_sites(array ('id' => $detail['cid']), array (
                        'column' => 'recieve_quantity',
                        'data'   => intval($arrival_quantity[$key])
                    ));

                //2.查询采购状态以及采购数量   逻辑修改 只要状态>=20 <70 就可以一直收货
                if (array_key_exists($detail['sku'], $update_sku)) {
                    $condition     = array ('id' => $detail['detailsid']);
                    $datail_status = $this->Purchaseorder_details->Purchaseorder_details->where($condition)
                        ->field('quantity,recieve_quantity,status')
                        ->find();
                    //先修改逻辑
                    if ($datail_status['status'] == 20 || $datail_status['status'] == 40 || $datail_status['status'] == 50 || $datail_status['status'] == 60 || $datail_status['status'] == 65) {
                        //2.1.   20 已打印   40未完全到货   收货数量=当前收货数+原收货数(应判断其与采购数大小)
                        $recieve_quantity = $update_sku[$detail['sku']] + $datail_status['recieve_quantity'];
                        if ($recieve_quantity < $datail_status['quantity']) {
                            $status = 40;
                        } elseif ($recieve_quantity >= $datail_status['quantity'] && $datail_status['status'] != 60 && $datail_status['status'] != 65) {
                            $status = 50;
                        } elseif ($datail_status['status'] == 60 || $datail_status['status'] == 65) {
                            $status = $datail_status['status'];
                        }
                    }
                    $update_data = array (
                        'recieve_quantity' => $recieve_quantity,
                        'status'           => $status
                    );
                    $judge       = $this->Purchaseorder_details->update_purchaseorder_details($condition, $update_data);

                    //如果不是新品  插入到sku属性确认表
                    if ($skuLogistic) {
                        $skuLogistic_data = array (
                            'poId'            => $_array[0]['id'],
                            'recieveDetailId' => $this->Recieve_details->Recieve_details_id,
                            'sku'             => $detail['sku'],
                            'skuLogistic'     => $skuLogistic,
                        );
                        D('AttrLog', 'Model')->addLog($skuLogistic_data);
                    }
                    unset($update_sku[$detail['sku']]);
                }
            }
        }
        if ($this->Recieve_details->Recieve_details_id && $judge) {
            $model->commit();
            return $this->Recieve_details->Recieve_details_id;
        } else {
            $model->rollback();
            return FALSE;
        }
    }

    /**
     * 根据采购单号获取收货单信息
     * 收货明细页面  共用
     */
    public function get_recieveinfo_by_id ($_array = array (), $flag = TRUE) {
        $_array = empty($_array)?$_GET:$_array;
        $model  = $this->Recieve_details->get_recieve_invoices_model($_array, $flag);
        if ($flag) {
            $Recieve_details = clone $model;
            $this->count     = $Recieve_details->count();//数量
            $Page            = new \Org\Util\Page($this->count, 20);// 实例化分页类 传入总记录数和每页显示的记录数(5)
            $this->page      = $Page->show();// 分页显示输出

            $model->order("a.recieve_time desc")
                ->limit($Page->firstRow.','.$Page->listRows);
        }
        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $result = $model->select();
        $result = $this->format_recieve_data($result);
        return $result;
    }

    /**
     * @param $_array
     * 收获修改数量
     */
    public function get_recieveinfo ($_array) {
        $result = $this->Recieve_details->get_recieveinfo_model($_array);
        $result = $this->format_recieve_data($result);
        return $result;
    }

    /**
     * 已收货待入库的采购单数据
     */
    public function get_recieved_wait_storage ($_array = array (), $flag = TRUE) {
        $_array = empty($_array)?$_GET:$_array;
        $model  = $this->Recieve_details->get_recieve_purchase_model($_array, $flag);
        // print_r($model);exit;
        if ($flag) {
            $Recieve_details = clone $model;
            $this->count     = $Recieve_details->count();//数量
            $Page            = new \Org\Util\Page($this->count, 20);// 实例化分页类 传入总记录数和每页显示的记录数(5)
            $this->page      = $Page->show();// 分页显示输出

            $model->limit($Page->firstRow.','.$Page->listRows);
        }
        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $result = $model->order("b.id desc")
            ->select();
        $result = $this->format_recieve_data($result);
        return $result;
    }

    /**
     * 绑定批次号
     */
    public function update_batch_code ($arr) {
        $recieve_details_id = rtrim($arr['recieve_details_id'], ',');
        $batch_code         = trim($arr['batch_code']);
        $condition          = array (
            'id' => array (
                'in',
                $recieve_details_id
            )
        );
        return $this->Recieve_details->update_recieve_details($condition, array ('batch_code' => $batch_code));
    }


    /**
     * 格式化数据采购数据
     */
    public function format_purchased_wait_recieve ($data) {
        //格式化
        foreach ($data as &$_data) {
            $_data['purchase_id']        = PublicInfoService::get_user_name_by_id($_data['purchase_id']);
            $_data['export_tax_rebate']  = $_data['export_tax_rebate'] == 1?'出口退税':'非出口退税';
            $_data['status']             = PublicdataService::get_purchaseorders_details_status($_data['status']);
            $_data['createtype']         = $_data['export_tax_rebate'] == 1?'手工创建':'预警生成';
            $_data['transfer_hopper_id'] = PublicdataService::get_transfer_hopper_name($_data['transfer_hopper_id']);
            $_data['supplier_id']        = PublicdataService::get_supplier_name($_data['supplier_id']);
            $sites                       = PublicInfoService::get_site_array();
            $_data['site_id']            = $sites[$_data['site_id']];
        }
        return $data;
    }


    /**
     * 格式化数据采购数据
     */
    public function recieve_pictureinfo ($data) {
        //格式化
        $infos    = $this->Recieve_manual_pics->get_recieve_manual_pics_model($data);
        $messages = array ();
        foreach ($infos as &$info) {
            $messages[$info['id']]['id']                 = $info['id'];
            $messages[$info['id']]['purchase_id']        = $info['purchaseorder_id'];
            $messages[$info['id']]['recieve_invoice_id'] = $info['recieve_invoice_id'];
            $messages[$info['id']]['reciever']           = PublicdataService::get_user_name($info['reciever_id']);
            $messages[$info['id']]['recieve_time']       = $info['recieve_time'];
            $messages[$info['id']]['uploader']           = PublicdataService::get_user_name($info['uploader']);
            $messages[$info['id']]['upload_time']        = $info['upload_time'];
            $messages[$info['id']]['details']            = $info['details'];
        }
        return $messages;
    }

    /**
     * @param $data
     * @return mixed
     * 格式化收货数据
     */
    public function format_recieve_data ($data) {
        $company_arr = PublicInfoService::get_company_array();
        //格式化
        foreach ($data as &$_data) {
            $_data['recieve_man'] = PublicInfoService::get_user_name_by_id($_data['recieve_man']);
            //$_data['store'] = $_data['store']==0?'国内仓':'海外仓';
            $_data['enterprise_dominant'] = $company_arr[$_data['enterprise_dominant']];
            $_data['transfer_hopper_id']  = PublicdataService::get_transfer_hopper_name($_data['transfer_hopper_id']);
            $_data['export_tax_rebate']   = $_data['export_tax_rebate'] == 1?'出口退税':'非出口退税';;
            $_data['supplier']    = PublicdataService::get_supplier_name($_data['supplier']);
            $_data['purchase_id'] = PublicInfoService::get_user_name_by_id($_data['purchase_id']);
            $_data['status']      = PublicdataService::get_purchaseorders_details_status($_data['status']);
            $sites                = PublicInfoService::get_site_array();
            $_data['site_id']     = $sites[$_data['site_id']];
        }
        return $data;
    }

    /**
     * @param $data
     * 已收货待入库的采购单下载
     */
    public function download ($data, $which_select) {

        $title    = $this->which_title($which_select);
        $fileName = $title['filename'];
        set_time_limit(0);
        ini_set('memory_limit', '2048M');
        header("Content-Type: application/csv");
        header("Content-Disposition: attachment;filename=$fileName");
        $file = fopen('php://output', 'w') or die("can't open php://output");
        fputcsv($file, $title['title']);
        unset($title['title']);
        foreach ($data AS $key => $val) {
            $down = $this->which_body($which_select, $val);
            fputcsv($file, $down);
            unset($down);
        }
        //关闭文件句柄
        fclose($file) or die("can't close php://output");
        exit;
        unset($data);
    }

    /**
     * @param $which_select
     * @return array
     * 下载表头以及表名
     */
    public function which_title ($which_select) {
        switch ($which_select) {
            case 'purchased_wait_recieve_download':
                $title = array (
                    'title'    => array (
                        '采购单号',
                        '退税类型',
                        'SKU',
                        '中文名称',
                        '规格',
                        '储位',
                        '供应商',
                        '采购员',
                        '采购数量',
                        '采购时间',
                        '采购明细单状态',
                        '采购类型',
                        '已到货数量',
                        '已入库量',
                        '退回量',
                        '站点',
                        '备注',
                    ),
                    'filename' => '已采购待收货的采购单.csv',
                );
                break;
            case 'recieve_details_download':
                $title = array (
                    'title'    => array (
                        '收货明细单号',
                        '采购单号',
                        '批次号',
                        'SKU',
                        '中文名称',
                        '规格',
                        '储位',
                        '供应商',
                        '采购数量',
                        '到货量',
                        '采购员',
                        '是否出口退税',
                        '收货日期',
                        '站点',
                        '公司主体',
                        '采购开发',
                        '到货次数',
                        '历史不良仓数量',
                        '历史退款率',
                    ),
                    'filename' => '已收货明细报表.csv',
                );
                break;
            case 'recieved_wait_storage_download':
                $title = array (
                    'title'    => array (
                        '采购单号',
                        '收货单号',
                        '收货明细单号',
                        '批次号',
                        'SKU',
                        'SKU中文名称',
                        '采购数',
                        '收货数',
                        '质检数',
                        '所属仓库',
                        '收货人',
                        '收货时间',
                        '站点',
                        '状态',
                    ),
                    'filename' => '已收货待入库的采购单.csv',
                );
                break;
            case 'delivery_details_download':
                $title = array (
                    'title'    => array (
                        '站点',
                        '出库单号',
                        '出库类型',
                        'shipmentId',
                        '出库时间',
                        'SKU',
                        '采购名称',
                        '数量',
                        '亚马逊配送网络sku',
                        '是否出口退税',
                        '储位',
                        '成本单价',
                        '成本金额',
                        '销售员',
                        '操作人',
                        '公司主体',
                        '备注'
                    ),
                    'filename' => '出库明细.csv',
                );
                break;
        }
        return $title;
    }

    /**
     * @param $which_select
     * @return array
     * 下载内容选择
     */
    public function which_body ($which_select, $val) {
        isset($val['sku_name']) && $val['sku_name'] = str_replace(array("\r\n", "\r", "\n", '<br/>', '<br>'), '', $val['sku_name']);
        switch ($which_select) {
            case 'purchased_wait_recieve_download':
                $body = array (
                    $val['id'],
                    $val['export_tax_rebate'],
                    $val['sku'],
                    $val['sku_name'],
                    $val['sku_standard'],
                    $val['storage_position'],
                    $val['supplier_id'],
                    $val['purchase_id'],
                    $val['quantity'],
                    $val['purchase_time'],
                    $val['status'],
                    $val['createtype'],
                    $val['recieve_quantity'],
                    $val['ware_quantity'],
                    $val['return_quantity'],
                    $val['site_id'],
                    $val['remark']
                );
                break;
            case 'recieve_details_download':
                $body = array (
                    $val['id'],
                    $val['purchaseorder_id'],
                    $val['batch_code'],
                    $val['sku'],
                    $val['sku_name'],
                    $val['sku_standard'],
                    $val['storage_position'],
                    $val['supplier'],
                    $val['purchase_quantity'],
                    $val['arrival_quantity'],
                    $val['purchase_id'],
                    $val['export_tax_rebate'],
                    $val['recieve_time'],
                    $val['site_id'],
                    $val['enterprise_dominant'],
                    PublicInfoService::getPuNameForSku($val['sku']),
                    $this->skuRecNum($val['sku']),
                    $this->skuBadNum($val['sku']),
                    ''
                );
                break;
            case 'recieved_wait_storage_download':
                $body = array (
                    $val['purchaseorder_id'],
                    $val['mainid'],
                    $val['id'],
                    $val['batch_code'],
                    $val['sku'],
                    $val['sku_name'],
                    $val['purchase_quantity'],
                    $val['arrival_quantity'],
                    $val['check_count'],
                    $val['store'],
                    $val['recieve_man'],
                    $val['recieve_time'],
                    $val['site_id'],
                    $val['status']
                );
                break;
            case 'delivery_details_download':
                $body = array (
                    $val['site_id'],
                    $val['id'],
                    $val['type'],
                    $val['shipmentid'],
                    $val['delivery_date'],
                    $val['sku'],
                    $val['sku_name'],
                    $val['quantity'],
                    $val['fnsku'],
                    $val['export_tax_rebate'],
                    $val['storage_position'],
                    $val['single_price'],
                    $val['cost'],
                    $val['seller_id'],
                    $val['delivery_man'],
                    $val['enterprise_dominant'],
                    $val['remark']
                );
                break;
        }
        return $body;
    }

    /**
     * 生成批次号
     */
    public function create_batch_code () {
        $last_code = D('Batches', 'Model')->get_batch_code();
        if (substr($last_code, 2, 8) == date('Ymd', time())) {
            $number     = intval(substr($last_code, - 2)) + 1;
            $batch_code = 'PC'.date('Ymd', time()).sprintf("%02d", $number);
        } else {
            $batch_code = 'PC'.date('Ymd', time()).'01';
        }
        $data = array (
            'batch_code' => $batch_code,
            'created'    => $this->nowtime,
            'userid'     => $_SESSION['current_account']['id'],
        );
        if (D('Batches', 'Model')->add_batch_code($data)) {
            return $batch_code;
        } else {
            return FALSE;
        }
    }

    /**
     * 检查批次号输入是否正确
     */
    public function check_batch_code ($batch_code) {
        return D('Batches', 'Model')->batches->where(array ('batch_code' => $batch_code))
            ->count();
    }

    /**
     * @param $_array
     * @return mixed
     * 收货修改sku已收货数量
     */
    public function find_check_info ($_array) {
        //当前收获数量
        $new_arrival_quantitys = explode(',', rtrim($_array['new_arrival_quantity'], ','));
        $site_id               = PublicInfoService::get_site_id(trim($_GET['site_id']));

        $new_total_recieve_nums = array_sum($new_arrival_quantitys);//除质检外的将收货数

        //修改收获明细
        $recieve_details_ids = explode(',', rtrim($_array['recieve_details_id'], ','));
        foreach ($recieve_details_ids as $key => $id) {
            $data = array ('arrival_quantity' => $new_arrival_quantitys[$key]);
            $this->Recieve_details->Recieve_details->where(array ('id' => $id))
                ->save($data);
        }

        //修改采购明细站点表   当前收获数+质检数
        $site_condition = array (
            'site_id'          => $site_id,
            'purchaseorders_id' => trim($_array['purchaseorder_id']),
            'sku'              => trim($_array['sku'])
        );
        $pre_check_quantity = $this->Purchaseorder_details_sites->purchaseorder_details_sites
            ->where($site_condition)->getField('check_quantity');
        $this->Purchaseorder_details_sites->update_purchaseorder_details_sites($site_condition,
            array ('recieve_quantity' => $new_total_recieve_nums + $pre_check_quantity));

        //查出非等于当前站点的收获明细的收获数
        $other_recieve_nums = $this->Purchaseorder_details_sites->purchaseorder_details_sites->where(
            array (
                'site_id'          => array('neq',$site_id),
                'purchaseorders_id' => trim($_array['purchaseorder_id']),
                'sku'              => trim($_array['sku'])
        ))->getField('sum(recieve_quantity)');

        //当前站点的总质检数
        $my_check_nums = $this->Purchaseorder_details_sites->purchaseorder_details_sites->where(
            array (
                'site_id'          => $site_id,
                'purchaseorders_id' => trim($_array['purchaseorder_id']),
                'sku'              => trim($_array['sku'])
            ))->getField('sum(check_quantity)');
        //根据采购单号 sku 查出原收货数
        $purchase_condition = array (
            'purchaseorder_id' => trim($_array['purchaseorder_id']),
            'sku'              => trim($_array['sku'])
        );
        $total_recieve_nums = $this->Purchaseorder_details->Purchaseorder_details->where($purchase_condition)
            ->field('recieve_quantity,quantity,status,check_quantity')
            ->find();
        //将收获数：当前站点的总质检数+将收获数+非当前站点的收获明细的收获数
        $recieve_quantity_to = $new_total_recieve_nums + $other_recieve_nums + $my_check_nums;
        if ($recieve_quantity_to > $total_recieve_nums['quantity']) {
            if ($total_recieve_nums['status'] <= 50) {
                $total_recieve_nums['status'] = 50;
            }
        } else {
            if ($total_recieve_nums['status'] <= 50) {
                $total_recieve_nums['status'] = 40;
            }
        }
        $pur_data = array (
            'recieve_quantity' => $recieve_quantity_to,
            'status'           => $total_recieve_nums['status'],
        );
        //修改采购单
        $pur_res = $this->Purchaseorder_details->update_purchaseorder_details($purchase_condition, $pur_data);
        if ($pur_res) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    /**
     * @param $privateSku
     * @return array
     * 获取SKU分主体在途库存
     */
    public function getInternalOnWayStock($privateSku) {
        if(empty($privateSku) || !is_array($privateSku))return array();
        $enterpriseDominants = PublicInfoService::get_company_array();
        $enterpriseDominantIds = array_keys($enterpriseDominants);
        $onWayStocks = D('Warehouse/PurchaseOrders','Model')->getInternalOnWayStock($privateSku);
        $realInventories = M('real_inventories', 'wms_', 'fbawarehouse')->field('sku, enterprise_dominant, SUM(quantity) AS actualStock')
            ->where('sku', array('IN', $privateSku))
            ->group('sku, enterprise_dominant')
            ->select();

        $formatOnWayStock = $formatRealInventory = array();
        foreach ($onWayStocks as $onWayStock) {
            $formatOnWayStock[$onWayStock['sku']][$onWayStock['enterprise_dominant']] = $onWayStock['onwayNum'];
        }

        foreach ($realInventories as $realInventorie) {
            $formatRealInventory[$realInventorie['sku']][$realInventorie['enterprise_dominant']] = $realInventorie['actualStock'];
        }

        $re = array();
        foreach ($privateSku as $sku) {
            foreach ($enterpriseDominantIds as $enterpriseDominantId) {
                if(isset($formatOnWayStock[$sku]['onWayStock'][$enterpriseDominantId]))
                    $re[$sku]['onWayStock'][$enterpriseDominantId] = $formatOnWayStock[$sku][$enterpriseDominantId];
                else
                    $re[$sku]['onWayStock'][$enterpriseDominantId] = 0;

                if(isset($formatRealInventory[$sku]['actualStock'][$enterpriseDominantId]))
                    $re[$sku]['actualStock'][$enterpriseDominantId] = $formatRealInventory[$sku][$enterpriseDominantId];
                else
                    $re[$sku]['actualStock'][$enterpriseDominantId] = 0;
            }
        }

        return $re;
    }

    /**
     * 描述：查历史数据表数据
     * 作者：橙子
     */
    public function check_history_order($checkData) {
        $msg = array();
        $historyPurchaseOrderCache = S('historyPurchaseOrderCache');
        if (!$historyPurchaseOrderCache or !is_array($historyPurchaseOrderCache)) {
            $historyPurchaseOrder = M('fba_shipment_purchaseorder_history', ' ', 'fbawarehouse')
                ->field('sku,enterprise_dominant')
                ->group('sku,enterprise_dominant')
                ->select();
            foreach ($historyPurchaseOrder as $val) {
                $historyPurchaseOrderCache[$val['sku'] . ':' . $val['enterprise_dominant']] = TRUE;
            }

            S('historyPurchaseOrderCache', $historyPurchaseOrderCache, 3600);

        }
        isset($historyPurchaseOrderCache[$checkData['sku'] . ':' . $checkData['enterprise_dominant']]) &&
        $msg[$checkData['enterprise_dominant']] = TRUE;

        $historyHzPurchaseOrderCache = S('historyHzPurchaseOrderCache');
        if (!$historyHzPurchaseOrderCache or !is_array($historyHzPurchaseOrderCache)) {
            $historyHzPurchaseOrderCache = M('fba_shipment_purchaseorder_history_hangzhou', ' ', 'fbawarehouse')
                ->field('sku')
                ->group('sku')
                ->select();
            foreach ($historyHzPurchaseOrderCache as $val) {
                $historyHzPurchaseOrderCache[$val['sku']] = TRUE;
            }

            S('historyHzPurchaseOrderCache', $historyHzPurchaseOrderCache, 3600);


        }
        isset($historyHzPurchaseOrderCache[$checkData['sku'] ]) && $msg[2] = TRUE;
        return $msg;

    }

    /**
     * 描述：检查实时表数据
     * 作者：橙子
     */
    public function check_timely_order($checkData) {
        $msg = array();
        $result = $this->Purchaseorder_details->check_purchase_order($checkData);
        !empty($result) && $msg[$checkData['sku'] . ':' . $checkData['enterprise_dominant']] = TRUE;

        return $msg;
    }
    /**
     * 描述:根据sku查找到货次数
     * 作者:kelvin
     */
    public function skuRecNum($sku){
        $model = M('wms_recieve_invoices',' ','fbawarehouse');
        $rec = $model->join('wms_recieve_details  ON wms_recieve_invoices.id = wms_recieve_details.recieve_invoice_id')
            ->where("sku = '$sku'")->group('purchaseorder_id,sku')->select();
        return count($rec);
    }
    /**
     * 描述:根据sku获取不良品数量
     * 作者:kelvin
     */
    public function skuBadNum($sku)
    {
        $model = M('wms_deliveryorders',' ','fbawarehouse')->where("sku = '$sku' AND type=50")->sum('quantity');
        return $model?$model:0;
    }
}